import React, { Component } from 'react'
import styles from "../assets/styles/car.module.css"

export default class TabC extends Component {
    state = {
        carNumbers: [
        ]
    }
    componentDidMount() {
        this.createCarNumber()
    }
    pause = () => {
        if (this.timmer) {
            clearInterval(this.timmer)
            this.timmer = null
        } else {
            this.createCarNumber()
        }

    }
    createCarNumber = () => {
        this.timmer = setInterval(() => {
            let temp = []
            for (let index = 0; index < 6; index++) {
                const obj = this.begin()
                temp.push(obj)
            }
            this.setState({
                carNumbers: temp
            })
        }, 300);
    }
    /**
     * 产生一个车牌 
     * return 车牌
     */
    begin = () => {
        let array = []
        //产生三个数字
        for (let index = 0; index < 3; index++) {
            const data = Math.floor(Math.random() * 10)
            array.push(data)
        }
        //产生两个字母 65开始 65 + 26
        for (let index = 0; index < 2; index++) {
            const data = Math.floor(Math.random() * 26 + 65)
            const chart = String.fromCharCode(data)
            array.push(chart)
        }
        //乱序 a后一个 b表示前一个
        array.sort((a, b) => {
            return Math.random() - 0.5
        })
        let obj = {
            name: "川A " + array.join(""),
            state: false
        }
        return obj

    }
    changeStateEvent = (name) => {
        const { carNumbers } = this.state
        carNumbers.forEach(item => item.state = false)
        const index = carNumbers.findIndex(item => item.name == name)
        carNumbers[index].state = true
        this.setState({
            carNumbers
        })
    }
    componentWillUnmount() {
        clearInterval(this.timmer)
    }
    render() {
        const { carNumbers } = this.state
        return (
            <div>
                <h2>车牌选好号</h2>
                <ul>
                    {carNumbers.map(item => {
                        return <li onClick={() => this.changeStateEvent(item.name)} className={item.state ? styles.active : ""} key={item.name}>{item.name}</li>
                    })}
                </ul>
                <p>你选中车牌：</p>
                <button onClick={this.pause}>暂停</button>
            </div>
        )
    }
}
